package enhance.redis.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import enhance.redis.util.RedisUtil;

/**
 * redis 配置类
 * @author xhl
 */
@Configuration
public class RedisAutoConfig extends CachingConfigurerSupport {

    /**
     * @Date: 2020/4/26 0026
     * @Author: thl
     * @Description: 使用fastjson序列化
     * @Param: [redisConnectionFactory]
     * @Return: org.springframework.data.redis.core.RedisTemplate<java.lang.Object,java.lang.Object>
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate( RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //使用fastjson序列化
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        // value值的序列化采用fastJsonRedisSerializer
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    /**
     * @Date: 2020/4/26 0026
     * @Author: thl
     * @Description: 用字符串序列化
     * @Param: [redisConnectionFactory]
     * @Return: org.springframework.data.redis.core.StringRedisTemplate
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate( RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    public RedisUtil redisUtil(RedisTemplate<String, Object> template){
        return new RedisUtil(template);
    }
}
